/**
 * Created by yyj on 2015/10/28.
 */

var path;
var waring_voice;
var error_voice;
var critical_voice;
var flag=true;
var isHHM = false;
var un="admin";
var pw=1;

$(function(){
    path = $("input[name=path]").val();
    //页面左侧内容宽度
    Reload();
   // initButton();//绑定按钮方法

    alarmMusic();//查询告警音乐

    pushAlarm();//使用websocket查询最新的告警信息

    selfAdaption();//iframe自适应高度
    $(window).resize(function() {
        selfAdaption();
    });

    //切换一级菜单选中状态
    $('.project_handover a').click(function(){
        $("#sys_name").text($(this).attr('remark'));
        $('.project_handover').find('a').removeClass('Selected');
        $(this).addClass('Selected');
        $('#nav>ul').stop().hide();
        $('.menu_l').show();
        $('.menu_l>div').hide();
        $('.'+$(this).attr('mark')).show();

        if($(this).attr('mark')=='logout_nav'){
            //注销
        }else if($(this).attr('mark')=='user_nav'){
            //编辑用户
        }else{
            if($(this).attr('url')!=''){
                //一级菜单跳转
                var remark = $(this).attr('mark').split('_');
                var nav = remark[0]+'_nav';
                var menu = remark[0]+'_menu';

                $('.'+nav).show();
                $('#platform_content').attr('src',$(this).attr('path')+$(this).attr('url'));
                $('.menu_l>.'+menu).show();
                $('.'+nav+'>.dropdown').removeClass('current');
                $('.'+nav+'>.dropdown').eq(0).addClass('current');
                $('.'+nav).find('.drop_current').removeClass('drop_current');
            }
        }
        $('.'+nav+ ' li:first a').click();
        Reload();

        //在radar界面显示控制台，其他界面隐藏
        var remark = $(this).attr("remark");
        if (remark == "RADAR"){
            openAlarmconsole();
        }else{
            $(".bottomlist").hide(0);
            $(".alert_box").hide(0);
        }
    });

    //子菜单页面导航点击选中效果
    $('.dropdown-menu a,.drophome a').click(function(){
        var index = $(this).parents('li').index();
        var name_nav = $(this).parents('ul').attr('class').split('_');
        var name_menu = name_nav[0]+'_menu';
        var li_herf = $('.'+name_menu).find('ul').eq(index).find('li').eq(0);

        /*
         * 下拉菜单版本
         * $('.dropdown-menu').find('.drop_current').removeClass('drop_current');
         */

        $(this).parent('li').addClass('drop_current');
        $(this).parents('ul').find('.dropdown').removeClass('current');
        $(this).parents('.dropdown').addClass('current');

        $('.'+name_menu).children('ul').each(function(){
            $(this).hide();
        });
        $('.'+name_menu).find('ul').eq(index).show();

        if($(li_herf).attr('url')!=''){
            $('#platform_content').attr('src',$(li_herf).attr('path')+$(li_herf).attr('url'));
        }else{
            $('#platform_content').attr('src',$(this).attr('path')+$(this).attr('url'));
        }
        Reload();
    });

    /**
     * top user 点击进入编辑密码页面
     * ${path }/sys/person_management/menuEditPassword.do
     */
    $(".top_user").click(function(){
        $('#platform_content').attr('src',path+"/sys/person_management/menuEditPassword.do");
    });

    //iframe切换
    $('.menu').click(function(){
        if($(this).attr('url')!=''){
            $('#menu_r').attr('src',$(this).attr('path')+$(this).attr('url'));
        };
    })

    //左侧导航切换
    $('.menu_l li').click(function(){
        $(this).siblings('li').removeClass('current');
        $(this).addClass('current');

        if($(this).attr('url')!=''){
            $('#platform_content').attr('src',$(this).attr('path')+$(this).attr('url'))
        };
    })

    //radar下方告警条
    $('.open').click(function(){
        var openhtml=$('.open').find('i').attr('title');
        if(openhtml=='打开'){
            $('.bottomlist').animate({height:'285px'});
            /*$('.bottomlist').css('height','auto');*/
            $('.open').find('i').attr('title','关闭').removeClass('shutup').addClass('shutdown')
        }else if(openhtml=='关闭'){
            $('.bottomlist').animate({height:'40px'});
            $('.open').find('i').attr('title','打开').removeClass('shutdown').addClass('shutup')
        }
    });

    //radar下方开启关闭消息
    $('.open1').click(function(){
        var openhtml=$('.open1').find('i').attr('title');
        if(openhtml=='关闭消息提醒'){
            $(this).find('i').attr('title','开启消息提醒').removeClass('open_message').addClass('close_message');
            $(".alert_box").hide();
        }else if(openhtml=='开启消息提醒'){
            $(this).find('i').attr('title','关闭消息提醒').removeClass('close_message').addClass('open_message');
            $(".alert_box").show();
        }
    });

    //radar下方开启关闭声音
    $('.open2').click(function(){
        var openhtml=$('.open2').find('i').attr('title');
        if(openhtml=='关闭声音提醒'){
            flag = false;
            $(this).find('i').attr('title','开启声音提醒').removeClass('open_sound').addClass('close_sound')
            $("#div1").html("");
        }else if(openhtml=='开启声音提醒'){
            flag = true;
            $(this).find('i').attr('title','关闭声音提醒').removeClass('close_sound').addClass('open_sound')
            $("#div1").html('<video controls="" autoplay="" name="media">'+
                '<source src="" type="audio/x-wav"></video>');
        }
    });
});


//开启页面下方控制台
function openAlarmconsole() {
    isHHM=true;

    $(".bottomlist").show();
    $(".alert_box").show();
    //1 获取radar中的告警数
    getAlarmNum();
    /**
     * 2 配置告警的url对应iframe中
     */
    $(".alarm_num li[title=critical]").click(function(){
        //window.location.href=path+"/hhm/alarmMessage/menu.do"
        $('#platform_content').attr('src',path+"/radar/alarmControl/initAlarmMsg.do?level=1&alarmState=0");
    });
    $(".alarm_num li[title=error]").click(function(){
        $('#platform_content').attr('src',path+"/radar/alarmControl/initAlarmMsg.do?level=2&alarmState=0");
    });
    $(".alarm_num li[title=warning]").click(function(){
        $('#platform_content').attr('src',path+"/radar/alarmControl/initAlarmMsg.do?level=3&alarmState=0");
    })
    //3 获取采集器告警信息
    getConsoleAlarm();

    //4 日志告警信息
    getSysLogAlarm();

    /**
     * “更多”按钮跳转
     */
    $("#alarmlist .press_btn1").click(function(){
        $('#platform_content').attr('src',path+"/radar/alarmControl/initAlarmMsg.do");
        $('.bottomlist').animate({height:'40px'});
        $('.open').find('i').attr('title','打开').removeClass('shutdown').addClass('shutup')
    });
    //日志的一会做
    // $("#loglist .press_btn1").click(function(){
    //     $('#platform_content').attr('src',path+"/hhm/loganalysis.do");
    //     $('.bottomlist').animate({height:'40px'});
    //     $('.open').find('i').attr('title','打开').removeClass('shutdown').addClass('shutup')
    // });
}

//获取日志告警
function getSysLogAlarm() {
    $.ajax({
        url:path + "/radar/syslog/getSysLogs.do",
        type:"POST",
        dataType:"json",
        data:{'pageSize':5,
            'pageNo':1},
        success:function(result){
            //2 故障信息
            //console.log(result);
            if(result.pageData!=null){
                var html=handlerTemplate({"data":result.pageData.pageList},"log-template");
                //console.log(html);
                $("#loglist .content_table tbody").html(html);
            }
        }
    });
}

//获取采集器告警信息
function getConsoleAlarm() {
    $("#alarmlist .content_table tbody").empty()
    $("#loglist .content_table tbody").empty();
    $.ajax({
        url:path + "/radar/alarmControl/pagingAlarmCollect.do",
        type:"POST",
        dataType:"json",
        data:{
            'pageSize':5,
            'pageNo':1,
            'alarmState':0 //展示“未解决”的告警信息
        },
        success:function(result){
            //2 故障信息
            //console.log(result);
            if(result.pageData!=null){
                var html=handlerTemplate({"data":result.pageData.pageList},"alarm-template");
                //console.log(html);
                $("#alarmlist .content_table tbody").html(html);
            }
        }
    });
}
//获取采集器告警个数
function getAlarmNum() {
    $.ajax({
        url:path + "/radar/alarmControl/getAlarmNum.do",
        type:"POST",
        dataType:"json",
        success:function(result){
            //2 故障类型分布\
            var map = result.data;
            if(map.level==null){
                $(".alarm_num li[title=critical]").text(0);
                $(".alarm_num li[title=error]").text(0);
                $(".alarm_num li[title=warning]").text(0);
            }else{
                $.each(map.level,function(key,value){
                    if(value.name=="Critical"){
                        $(".alarm_num li[title=critical]").text(value.value);
                    }else if(value.name=="Error"){
                        $(".alarm_num li[title=error]").text(value.value);
                    }else if(value.name=="Warning"){
                        $(".alarm_num li[title=warning]").text(value.value);
                    }
                });
            }
        }
    });
}

function pushAlarm(){

    var ws = new WebSocket("ws://"+socketIp+":"+socketPort);
    //var ws = new WebSocket("ws://192.168.20.166:9003");

    ws.onopen = function () {
        ws.send($("#staffId").val());
        console.log('Info: connection opened.');
    };
    ws.onmessage = function (event) {
        //控制告警弹窗个数2个
        var alarmTips = $(".alert_box").children();
        if(alarmTips.length>=2){
            alarmTips[alarmTips.length-1].remove();
        }
        if(isHHM){
            showPushAlarm(event.data); //展示推送消息
        }
    };
    ws.onclose = function (event) {
        console.log('Info: connection closed.');
    };
}

function showPushAlarm(alarmData) {
    var data = eval("(" + alarmData + ")");
    if (data.alarmMessage != null && data.alarmMessage){
        if(data.isSysLog=="no"){ //展示采集器告警信息
            var alarmLevel=data.alarmLevel;
            $(".alert_box").prepend(
                '<div class="alert fade in '+alarmLevel+'">'+
                '<button type="button" class="close" data-dismiss="alert">×</button>'+
                '<p>'+data.alarmMessage+'</p>'+
                '<a class="btn" href="javascript:viewAlarm('+data.alarmId+');">处理</a>'+
                '</div>');
            alarmVoice(alarmLevel);
            getAlarmNum();
            getSysLogAlarm();
            getConsoleAlarm();
        }else if(data.isSysLog=="yes") {//修改日志告警列表
            //pushAlarmDialog(jsonMsg);
            var sysLogAlarms = $("#sysLogAlarm").children();
            if (sysLogAlarms.length >= 5) {
                sysLogAlarms[sysLogAlarms.length - 1].remove();
            }
            $("#sysLogAlarm").prepend(
                '<tr>' +
                '<td>' + data.hostIp + '</td>' +
                '<td>' + data.alarmLevel + '</td>' +
                '<td>' + data.alarmType + '</td>' +
                '<td>' + data.lastAlarmTime + '</td>' +
                '<td>' + data.alarmMessage + '</td>' +
                '</tr>');
        }
    }

}

//展示告警信息的详细信息
function viewAlarm(id) {
    layer.open({
        extend:['skin/layer_iframe.css'],
        skin:'layer-ext-skin-layer_iframe.css',
        type:2,
        title:'查看详细数据',
        area:['800px','600px'],
        content:path + '/radar/alarmControl/showDetails.do?alarmId='+id,
        maxmin: true,
        shadeClose: true
    });
}

//告警声音提示
function alarmVoice(alarmLevel) {
    var name = "";
    if(alarmLevel.indexOf("warning") >= 0 && flag){
        name = waring_voice;
    }
    if(alarmLevel.indexOf("error") >= 0 && flag){
        name =  error_voice;
    }
    if(alarmLevel.indexOf("critical") >= 0 && flag){
        name =  critical_voice;
    }
    $("#div1").html('<video controls="" autoplay="" name="media">'+
        '<source src="'+name+'" type="audio/x-wav"></video>'
    );
}

//获取告警声音
function alarmMusic() {
    $.ajax({
        type : "post",
        dataType : "json",
        url : path +"/radar/alarmControl/alarmVoice.do",
        success : function(result){
            //var list = eval("("+result.list+")");
            var list = result.data;
            for(var i = 0; i < list.length; i++){
                if(list[i].alarmLevel.indexOf("warning") >= 0 ){
                    waring_voice = path+"/upload/voice/"+list[i].bell;
                }
                if(list[i].alarmLevel.indexOf("error") >= 0 ){
                    error_voice = path+ "/upload/voice/"+list[i].bell;
                }
                if(list[i].alarmLevel.indexOf("critical") >= 0 ){
                    critical_voice = path+ "/upload/voice/"+list[i].bell;
                }
            }
        }
    });
}

function Reload(){
	$('.menu_l').show();
    if($('.menu_l>div:visible ul:visible').attr('class')=='no_includeul'){
        $('.menu_l').hide();
    }else if($('.menu_l>div:visible ul:visible').attr('class')=='includeul'){
        $('.menu_l').show();
    }else{
    	$('.menu_l').hide();
    }
    selfAdaption();

}


function selfAdaption(){
    var clientHeight=document.documentElement.clientHeight;
    var height=(parseInt(clientHeight)-93)+"px";
    var width = $('.menu_l').width();
    if($('.menu_l').css('display')=='block'){
        width = 120
    }else{
        width= 0;
    }
    var clientWidth=document.documentElement.clientWidth;
    $("#platform_content").height(height).width((clientWidth-width-2)+'px');
}

/**
 * 模版处理方法
 * @param data
 * @returns {*}
 */
handlerTemplate=function(data,node){
    //注册一个Handlebars模版，通过id找到某一个模版，获取模版的html框架
    var template = Handlebars.compile($("#"+node).html());
    //console.log($("#"+node).html());
    //注册一个翻译用的Helper，0翻译成男，1翻译成女
    Handlebars.registerHelper("transformat",function(value){
        //sysEcho(value);
        if(value==false){
            return "否";
        }else if(value==true){
            return "是";
        }
    });
    //时间戳转换时间格式
    Handlebars.registerHelper("prettifyDate", function(timestamp) {
        //format("yyyy-MM-dd HH:mm:ss");
        return formatDateTime(new Date(parseInt(timestamp)));
        //return (new Date(parseInt(timestamp))).toLocaleString().substr(0,17);
    });
    /**
     * 处理select option选择
     */
    window.Handlebars.registerHelper('select', function( value, options ){
        //sysEcho(value);
        var $el = $('<select />').html( options.fn(this) );
        $el.find('[value="' + value + '"]').attr({'selected':'selected'});
        return $el.html();
    });
    /**
     * 处理isping issyslog 勾选
     */
    Handlebars.registerHelper("selectcheckbox", function(value) {
        //sysEcho(value);
        var result="";
        if(value===true){
            result="checked";
        }
        return result
    });
    /**
     * 处理null
     */
    Handlebars.registerHelper("dealNull", function(value) {
        //sysEcho(value);
        var result=value;
        if(value=="null"){
            result="";
        }
        return result
    });
    /**
     * 处理告警类型
     * 0 配置 1 性能 2 容量 3 状态 4 服务  5 进程 6 温度
     */
    Handlebars.registerHelper("dealAlarmType", function(value) {
        //sysEcho(value);
        var result=value;
        switch(value)
        {
            case 0:
                result="配置";
                break
            case 1:
                result="性能";
                break
            case 2:
                result="容量";
                break
            case 3:
                result="状态";
                break
            case 4:
                result="服务";
                break
            case 5:
                result="进程";
                break
            case 6:
                result="温度";
                break
            default :
                result="未知";
        }
        return result
    });

    /**
     * 处理告警级别
     * 告警级别 1CRITICA  2 ERROR 3 WARNING
     */
    Handlebars.registerHelper("dealAlarmLevel", function(value) {
        //sysEcho(value);
        var result=value;
        switch(value)
        {
            case 1:
                result="CRITICA";
                break
            case 2:
                result="ERROR";
                break
            case 3:
                result="WARNING";
                break
            default :
                result="未知";
        }
        return result
    });
    /**
     * 处理告警状态
     * 告警状态 0未处理 1 已处理  2 忽略
     */
    Handlebars.registerHelper("dealAlarmState", function(value) {
        //sysEcho(value);
        var result=value;
        switch(value)
        {
            case 0:
                result="未处理";
                break
            case 1:
                result="已处理";
                break
            case 2:
                result="忽略";
                break
            default :
                result="未知";
        }
        return result
    });
    return template(data);
}

